<?php

namespace services\common;

use Yii;
use common\models\marketing\OutpatientType;
use common\models\patient\User;
use common\components\Service;
use common\helpers\CommonHelper;
use common\models\common\Config;

/**
 * Class ConfigService
 * @package services\common
 */
class ConfigService extends Service
{
    /**
     * 根据ID查找信息
     *
     * @param int $id
     * @return Config|null
     */
    public function findById(int $id = 0): ?Config
    {
        return Config::find()->where(['id' => $id])->one();
    }

    /**
     * 查找信息
     *
     * @param array $condition
     * @return Config|null
     */
    public function findInfo(array $condition = []): ?Config
    {
        $query = Config::find();

        isset($condition['config_name']) && $query->andWhere(['config_name' => $condition['config_name']]);
        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);

        return $query->one();
    }

    /**
     * 查找列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = Config::find();

        // select
        isset($condition['select']) && $query->select($condition['select']);

        // condition
        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->asArray()->all();
    }

    /**
     * @return array
     */
    public function getList($projectId)
    {
        $configList = Config::find()
            ->select('id, config_name, config_value, remark')
            ->where(['project_id' => $projectId])
            ->asArray()
            ->all();
        $configArr = [];
        foreach ($configList as $val) {
            $arr = [$val['config_name'] => $val['config_value']];
            $configArr[] = $arr;
        }
        return $configArr;
    }

    /**
     * 编辑全局设置
     *
     * @param $params
     * @return array|mixed
     */
    public function update($params)
    {
        Config::updateAll(
            ['config_value' => $params['global_initial_visit_time']],
                ['config_name' => Config::CONFIG_NAME_VISIT, 'project_id' => $params['project_id']]
        );
        Config::updateAll(
                ['config_value' => $params['global_no_therapy_time']],
                ['config_name' => Config::CONFIG_NAME_NO_THERAPY, 'project_id' => $params['project_id']]
        );
        Config::updateAll(
            ['config_value' => $params['global_loss_amout_money']],
                ['config_name' => Config::CONFIG_NAME_LOSS_MONEY, 'project_id' => $params['project_id']]
        );
        Config::updateAll(
            ['config_value' => $params['global_card_consult']],
            ['config_name' => Config::CONFIG_NAME_CARD, 'project_id' => $params['project_id']]
        );
        Config::updateAll(
            ['config_value' => $params['global_card_introduce']],
            ['config_name' => Config::CONFIG_NAME_CARD_INTRODUCE, 'project_id' => $params['project_id']]
        );
        Config::updateAll(
            ['config_value' => $params['global_customer_outpatient_type']],
            ['config_name' => Config::CONFIG_NAME_CUSTOMER_OUTPATIENT, 'project_id' => $params['project_id']]
        );

        // 咨询号（前）匹配到的患者的就诊类型修改为咨询号类型
        $this->updateOutpatientType($params['global_card_consult'], $params['project_id']);

        // 介绍号（前）匹配到的患者修改为是介绍号
        $this->updateIsIntroduce($params['global_card_introduce'], $params['project_id']);
        return true;
    }

    /**
     * 编辑全局设置
     *
     * @param $params
     * @return array|mixed
     */
    public function updateConfig($params)
    {
        $transaction = Yii::$app->db->beginTransaction();
        try{
            // 项目中设置的条数
            $configIs = Config::find()->where(['project_id' => $params['project_id']])->count();

            // 咨询号
            $params['global_card_consult'] = Yii::$app->services->bodyParts->strFormat($params['global_card_consult']);

            // 介绍号
            $params['global_card_introduce'] = Yii::$app->services->bodyParts->strFormat($params['global_card_introduce']);

            // 都存在时只更新
            if ($configIs == 6) {
                $this->update($params);
            } else {
                $this->create($params);
            }
            $transaction->commit();
            return ['code' => 200, 'message' => '修改成功'];
        } catch (\Exception $e) {
            $transaction->rollBack();
            return CommonHelper::api(422, $e->getMessage());
        }

    }

    /**
     * @Notes: 项目没有时就新增
     *
     * @Interface create
     * @param $params
     * @return array|mixed
     */
    public function create($params)
    {
        $configVisitIs = Config::findOne(['config_name' => Config::CONFIG_NAME_VISIT, 'project_id' => $params['project_id']]);
        $configTherapyIs = Config::findOne(['config_name' => Config::CONFIG_NAME_NO_THERAPY, 'project_id' => $params['project_id']]);
        $configLossIs = Config::findOne(['config_name' => Config::CONFIG_NAME_LOSS_MONEY, 'project_id' => $params['project_id']]);
        $configCardIs = Config::findOne(['config_name' => Config::CONFIG_NAME_CARD, 'project_id' => $params['project_id']]);
        $configCardIntroduceIs = Config::findOne(['config_name' => Config::CONFIG_NAME_CARD_INTRODUCE, 'project_id' => $params['project_id']]);
        $configCustomerIs = Config::findOne(['config_name' => Config::CONFIG_NAME_CUSTOMER_OUTPATIENT, 'project_id' => $params['project_id']]);
        $config = [];
        if (!$configVisitIs) {
            $config[] = [
                'config_name' => 'global_initial_visit_time',
                'config_value' => $params['global_initial_visit_time'],
                'remark' => Config::CONFIG_REMARK_VISIT,
            ];
        }
        if (!$configTherapyIs) {
            $config[] = [
                'config_name' => 'global_no_therapy_time',
                'config_value' => $params['global_no_therapy_time'],
                'remark' => Config::CONFIG_REMARK_NO_THERAPY,
            ];
        }
        if (!$configLossIs) {
            $config[] = [
                'config_name' => 'global_loss_amout_money',
                'config_value' => $params['global_loss_amout_money'],
                'remark' => Config::CONFIG_REMARK_LOSS_MONEY,
            ];
        }
        if (!$configCardIs) {
            $config[] = [
                'config_name' => 'global_card_consult',
                'config_value' => $params['global_card_consult'],
                'remark' => Config::CONFIG_REMARK_CARD,
            ];
        }
        if (!$configCardIntroduceIs) {
            $config[] = [
                'config_name' => 'global_card_introduce',
                'config_value' => $params['global_card_introduce'],
                'remark' => Config::CONFIG_REMARK_CARD_INTRODUCE,
            ];
        }
        if (!$configCustomerIs) {
            $config[] = [
                'config_name' => 'global_customer_outpatient_type',
                'config_value' => $params['global_customer_outpatient_type'],
                'remark' => Config::CONFIG_REMARK_CUSTOMER_OUTPATIENT,
            ];
        }
        if ($config) {
            $addList = [];
            foreach ($config as $val) {
                $add['config_name'] = $val['config_name'];
                $add['config_value'] = $val['config_value'];
                $add['remark'] = $val['remark'];
                $add['project_id'] = $params['project_id'];
                $add['created_at'] = time();
                $add['updated_at'] = time();
                $addList[] = $add;
            }
            Yii::$app->db->createCommand()
                ->batchInsert(Config::tableName(),
                    ['config_name', 'config_value', 'remark', 'project_id', 'created_at', 'updated_at'],
                    $addList)
                ->execute();
        }
        return $this->update($params);
    }


    /**
     * @Notes: 咨询号（前）匹配到的患者的就诊类型修改为咨询号类型
     *
     * @Interface updateOutpatientType
     * @param $cardConsult
     * @return bool|int
     */
    public function updateOutpatientType($cardConsult, $projectId)
    {
        $cardConsultArr = explode(',', $cardConsult);

        // 咨询号字段没有数据时，直接返回
        if (!$cardConsultArr[0]) {
            return true;
        }

        // 查询当前项目就诊类型有没有咨询号
        $outpatientTypeZx = OutpatientType::findOne([
            // 'project_id' => $projectId,
            'outpatient_name' => '咨询号',
            'status' => OutpatientType::STATUS_ENABLE
            ]);

        if (!$outpatientTypeZx) {
            return CommonHelper::api(422, '当前项目没有咨询号就诊类型或已停用');
        }

        $whereArr = ['or'];
        foreach ($cardConsultArr as $val) {
            $whereArr[] = ['like', 'patient_card_id', $val.'%', false];
        }

        $searchUserHave = User::find()
            ->select('id, patient_card_id')
            ->where($whereArr)
            ->andWhere(['project_id' => $projectId])
            ->andWhere(['!=', 'outpatient_type_id', $outpatientTypeZx->id])
            ->asArray()
            ->all();

        if (!$searchUserHave) {
            return true;
        }
        $searchUserHaveIds = array_column($searchUserHave, 'id');
        return User::updateAll(
            ['outpatient_type_id' => $outpatientTypeZx->id], ['id' => $searchUserHaveIds]
        );
    }


    /**
     * @Notes: 介绍号（前）匹配到的患者修改为是介绍号
     *
     * @param $cardIntroduce
     * @param $projectId
     * @return bool|int
     */
    public function updateIsIntroduce($cardIntroduce, $projectId)
    {
        $cardIntroduceAttr = explode(',', $cardIntroduce);

        // 介绍号字段没有数据时，直接返回
        if (!$cardIntroduceAttr[0]) {
            return true;
        }

        $whereArr = ['or'];
        foreach ($cardIntroduceAttr as $val) {
            $whereArr[] = ['like', 'patient_card_id', $val.'%', false];
        }

        $searchUserHave = User::find()
            ->select('id, patient_card_id')
            ->where($whereArr)
            ->andWhere(['project_id' => $projectId])
            ->andWhere(['!=', 'is_introduce', User::IS_INTRODUCE_YES])
            ->asArray()
            ->all();

        if (!$searchUserHave) {
            return true;
        }
        $searchUserHaveIds = array_column($searchUserHave, 'id');
        return User::updateAll(
            ['is_introduce' => User::IS_INTRODUCE_YES], ['id' => $searchUserHaveIds]
        );
    }
}
